import requests
import re
from setenv import setLotteryDir
from setenv import getFileDir
from setenv import getFileName


def fetch_lotto_numbers(url):
    response = requests.get(url)
    setLotteryDir()
    ssqdir = getFileDir()
    ssqname = getFileName("ssqfilename")
    response = requests.get(url)
    if response.status_code == 200:
        html = response.text
        # with open( "/home/liumh/sbin/ss.txt", "w") as file:
        # # 写入数据
        #     file.write(str(html) + "\n")

        # file.close
        # 假设中奖号码在HTML中的某个特定标签内，例如：  <div class="ssqRed-dom">[25,10,07,14,21,01]</div>
        # 获取红色球
        numbers_pattern = re.compile(r'<div class="ssqRed-dom">\[(\d+,\d+,\d+,\d+,\d+,\d+)\]</div>', re.DOTALL)
        numbers_match = numbers_pattern.search(html)
        if numbers_match:
            numbers_html = numbers_match.group(1)
            # 假设中奖号码是HTML中的纯文本内容，我们可以使用 BeautifulSoup 来提取它
            from bs4 import BeautifulSoup
            soup = BeautifulSoup(numbers_html, 'html.parser')
            numbers = soup.get_text().strip('[').strip(']').split(',')
            # return numbers
        # 获取蓝色球    <div class="ssqBlue-dom">[07]</div>
        numbers_pattern = re.compile(r'<div class="ssqBlue-dom">\[(\d+)\]</div>', re.DOTALL)
        numbers_match = numbers_pattern.search(html)
        if numbers_match:
            numbers_html = numbers_match.group(1)
            # 假设中奖号码是HTML中的纯文本内容，我们可以使用 BeautifulSoup 来提取它
            from bs4 import BeautifulSoup
            soup = BeautifulSoup(numbers_html, 'html.parser')
            numbers2 = soup.get_text().strip().split()
            numresult = numbers + numbers2
        # 获取期数  <div class="ssqQh-dom">2024013</div>
        numbers_pattern = re.compile(r'<div class="ssqQh-dom">(\d+)</div>', re.DOTALL)
        numbers_match = numbers_pattern.search(html)
        if numbers_match:
            numbers_html = numbers_match.group(1)
            # 假设中奖号码是HTML中的纯文本内容，我们可以使用 BeautifulSoup 来提取它
            from bs4 import BeautifulSoup
            soup = BeautifulSoup(numbers_html, 'html.parser')
            datenum = soup.get_text().strip().split()
        numstr = ""
        for var in numresult:
            numstr = numstr + str(var) + " "
        # 使用上下文管理器打开文件
        print(datenum[0])
        with open( str(ssqdir) + "/" + str(ssqname) , "w") as file:
        # 写入数据
            file.write(numstr + "\n")

        file.close
        return numresult
    return None

if __name__ == '__main__':
    url = 'https://www.cwl.gov.cn/ygkj/wqkjgg/'  # 替换为实际的大乐透中奖号码公布页面URL
    numbers = fetch_lotto_numbers(url)
    if numbers:
        print("双色球中奖号码：", numbers)
    else:
        print("未能抓取到中奖号码。")